<template>
    <div>
        <el-form :model="tableFormInfo" ref="childTableInfo">
            <el-table :show-header="false" :data="tableFormInfo.nameData" stripe size="small" class="tableConfig">
                <el-table-column type="expand">
                    <template slot-scope="parentScope">
                        <el-table
                            :data="tableFormInfo.fieldData"
                            size="small" style="margin-left: 58px;width: 95%;">
                            <el-table-column prop="name" label="字段名" align="center">
                                <template slot="header">
                                    <el-tooltip class="item" effect="dark" content="*字段名以小写字母开头，不能有大写字母、汉字、空格" placement="top">
                                        <i class="el-icon-warning-outline" style="color:red;paddingRight:10px;"></i>
                                    </el-tooltip>字段名
                                </template>
                                <template slot-scope="scope">
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.name`"
                                    :rules="[{required:true,message:'请输入字段名',trigger:'blur'}, {validator:fieldNameValidator,trigger:'blur'}]">
                                        <el-input v-model.trim="scope.row.name"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column prop="length" label="长度(字符)" align="center">
                                <template slot="header">
                                    <span>
                                    <el-tooltip class="item" effect="dark" content="*已发布表单编辑时，修改数值不能小于上次数值" placement="top">
                                        <i class="el-icon-warning-outline" style="color:red;paddingRight:10px;"></i>
                                    </el-tooltip>长度(字符)
                                    </span>
                                </template>
                                <template slot-scope="scope">
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                        v-if="scope.row.format === 'varchar'"
                                        :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:(rule,value,callback)=>{
                                          lengthValidator(rule,value,callback,scope.row,formInfo)},trigger:'blur'}]">
                                        <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}">
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                        v-else-if="scope.row.format === 'longtext'"
                                        :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator2,trigger:'blur'}]">
                                        <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                        v-else-if="scope.row.format === 'int'"
                                        :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator: lengthValidator2,trigger:'blur'}]">
                                        <el-input v-model="scope.row.length" disabled>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                        v-else-if="scope.row.format === 'double'||scope.row.format === 'decimal'"
                                        :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator3,trigger:'blur'}]">
                                        <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                        v-else-if="scope.row.format === 'datetime'"
                                        :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator: lengthValidator2,trigger:'blur'}]">
                                        <el-input v-model="scope.row.length" disabled>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                        v-else-if="scope.row.format === 'time'"
                                        :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator2,trigger:'blur'}]">
                                        <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                        v-else
                                        :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator: lengthValidator3,trigger:'blur'}]">
                                        <el-input v-model="scope.row.length"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column prop="format" label="数据格式" align="center">
                                <template  slot-scope="scope">
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.format`">
                                        <el-select filterable remote v-model="scope.row.format" @change="e => formatChange(e, parentScope.$index, scope.$index)" disabled>
                                            <el-option v-for="(item,index) in dicData" :key="index" :label="item.label" :value="item.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column prop="desc" label="备注(标题)" align="center">
                                <template slot-scope="scope">
                                    <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.desc`">
                                        <el-input v-model="scope.row.desc" :disabled="true"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination background  :layout="layout" :total="tableFormInfo.fieldData.length" :page-sizes="pageSizes"
                            :current-page="configPage.pageNo" :page-size="configPage.pageSize" style="float:right;marginBottom:20px;"
                            @size-change="configSizeChange" @current-change="configCurrentChange">
                        </el-pagination>
                    </template>
                </el-table-column>
                <el-table-column prop="tableName" label="表名" align="center">
                    <template slot="header">
                        <el-tooltip class="item" effect="dark" content="*表名不能以数字，特殊字符串开头，不能有汉字" placement="top">
                            <i class="el-icon-warning-outline" style="color:red;paddingRight:10px;"></i>
                        </el-tooltip>表名
                    </template>
                    <template slot-scope="parentScope">
                        <el-form-item :prop="`nameData.${parentScope.$index}.tableName`"
                            :rules="[{required:true,message:'请输入表名',trigger:'blur'},{validator: tableNameValidator,trigger:'blur'}]">
                            <el-input v-model.trim="parentScope.row.tableName" placeholder="示例：table033378" @change="e => tableNameChange(e, parentScope.$index)"></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="tableRemark" label="备注" align="center">
                    <template slot-scope="parentScope">
                        <el-form-item>
                            <el-input v-model="parentScope.row.tableRemark" placeholder="备注" disabled></el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
    </div>
</template>
<script>
import { getTableListExcludeForm } from '../../../api/custom/formDesigner'
export default {
    name: 'ExpandTable',
    data () {
        return {
            tableFormInfo: {
                nameData: [],
                fieldData: []
            },
            configPage: {
                pageNo: 1, // 当前页数
                pageSize: 10 // 每页显示多少条
            },
            layout: 'prev, pager, next,sizes,jumper', //分页显示布局
            pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
            //字段数据类型
            dicData: [{
                label: '文本',
                value: 'varchar'
            },
            {
              label: '长文本',
              value: 'longtext'
            },
            {
                label: '整数',
                value: 'int'
            },
            {
                label: '小数',
                value: 'double'
            },
            {
                label: '小数-高精度',
                value: 'decimal'
            },
            {
                label: '时间日期',
                value: 'datetime'
            }, 
            {
              label: '时间',
              value: 'time'
            }],
        }
    },
    props: ['subFormListData', 'formInfo', 'updateFlag', 'formId','allComponments'],
    watch: {
        updateFlag () {
            this.init()
        }
    },
    destroyed () {
        this.tableFormInfo.nameData = []
        this.tableFormInfo.fieldData = []
    },
    methods: {
        init () {
            this.$nextTick(() => {
                if (this.subFormListData.length > 0) {
                    this.tableFormInfo.nameData = []
                    this.tableFormInfo.fieldData = []
                    this.subFormListData.forEach(item => {
                        this.tableFormInfo.nameData.push({
                            tableName: item.tableName,
                            tableRemark: item.tableRemark
                        })
                        this.tableFormInfo.fieldData = [...item.fieldData]
                    })
                } else {
                    this.tableFormInfo.nameData = []
                    this.tableFormInfo.fieldData = []
                }
            })
        },
        tableNameChange (e, line) {
            this.$emit('changeCountFunc', { value: e, row: line })
        },
        formatChange (value, tableIdx, rowIndex) {
            if (value === 'varchar') {
                this.tableFormInfo.fieldData[rowIndex].length = '50'
            } else if (value === 'double' || value === 'decimal') {
                this.tableFormInfo.fieldData[rowIndex].length = `16,${this.tableFormInfo.fieldData[rowIndex].decimalPlaces ? this.tableFormInfo.fieldData[rowIndex].decimalPlaces : 2}`
            } else {
                this.tableFormInfo.fieldData[rowIndex].length = '0'
            }
            // this.$emit('changeFormat', value, tableIdx, rowIndex)
        },
        configSizeChange (size) {
            this.configPage.pageSize = size
        },
        configCurrentChange (page) {
            this.configPage.pageNo = page
        },
        //字段名校验
        fieldNameValidator(rule, value, callback) {
            let pattern = /^[a-z][^\u4e00-\u9fa5A-Z ]+$/
            if (!pattern.test(value)) {
                callback(new Error('请输入符合要求的字段名'))
            } else if (value.length > 64){
                callback(new Error('长度不能超过64'))
            } else {
                let names = this.tableFormInfo.fieldData.filter((item) => {
                    return item.name === value
                })
                if (names.length > 1) {
                    callback(new Error('字段名重复'))
                } else {
                    callback()
                }
            }
        },
        //表名校验
        tableNameValidator(rule, value, callback) {
            let pattern = /^[a-z][^\u4e00-\u9fa5A-Z ]+$/
            if (!pattern.test(value)) {
                callback(new Error('请输入符合要求的表名'))
            } else if (value.length > 64){
                callback(new Error('长度不能超过64'))
            } else {
                if (!this.formInfo.id) { //新增
                    getTableListExcludeForm({tableName: value}).then((res) => {
                        if (res.code === 0 && res.data.includes(value.toLowerCase())) {
                            callback(new Error('表名已存在，请修改'))
                        } else {
                            callback()
                        }
                    }).catch(e => console.log('获取所有表名：', e))
                } else {
                    const childId = this.formInfo?.subFormListData.filter((_) => _.tableName == value)[0].tableId;
                    getTableListExcludeForm({ tableName: value,formId: childId}).then((res) => {
                        if (res.code === 0 && res.data.includes(value.toLowerCase())) {
                            callback(new Error('表名已存在，请修改'))
                        } else {
                            callback()
                        }
                    }).catch(e => console.log('获取除当前表单外的所有表名：', e))
                }
            }
        },
        //长度校验
        lengthValidator(rule, value, callback,row,item) {
          let pattern = /^[1-9][0-9]*$/
          let temp =[]  //子表单中的所有组件
          let element = [] //与当前行匹配的子表单中的组件
          if (!pattern.test(value)) {
            callback(new Error('请输入数字'))
          } else {
            this.allComponments.map((item,index)=>{
                if(item.__config__.children){
                  temp = item.__config__?.children[0]?.__config__?.children
                  element =  temp.filter((item)=>{return item.__vModel__ === row.name })
                }
              })
            let num = Number(value)
            if(element[0]&&element[0]['show-word-limit'] && value < Number(element[0].maxlength)){
              callback(new Error('长度不得小于限制输入字符长度'))
            } else if ( value > 1225) {
              callback(new Error('字符长度不能超过1225'))
            } else {
              if (this.isReference ) { //已发布
                if (this.currentLength.oldLength) {
                  if (this.currentLength.oldType === this.currentLength.format) { //同类型
                    let oldNum = Number(this.currentLength.oldLength)
                    if (num < oldNum) {
                      this.currentLength.length = this.currentLength.oldLength
                    }
                  }
                }
              }
              callback()
            }
          }
        },
        //长度校验
        lengthValidator2(rule, value, callback) {
            let pattern = /^[0]$/
            if (!pattern.test(value)) {
                callback(new Error('仅能为0'))
            } else {
                callback()
            }
        },
        //长度校验
        lengthValidator3(rule, value, callback) {
            let pattern = /^[1-9][0-9]{0,2},[0-9]$/
            if (!pattern.test(value)) {
                callback(new Error('请输入“总长度,小数位数”'))
            } else {
                let nums = value.split(',')
                if (Number(nums[0]) > 255) {
                    callback(new Error('总长度不能超过255'))
                } else {
                    callback()
                }
            }
        },
    }
}
</script>
<style lang="less" scoped>
/deep/.el-table__row{
    height: 50px !important;
}
</style>